package com.chahua.organized.handler;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.chahua.organized.dao.DepartmentMemberDao;
import com.chahua.organized.qo.DepartmentMemberInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chahua
 * @date 2022/4/9 23:23
 **/
@Component
public class MemberImportVerifyHandler implements IExcelVerifyHandler<DepartmentMemberInput> {

    private final ThreadLocal<List<DepartmentMemberInput>> threadLocal = new ThreadLocal<>();

    @Autowired
    private DepartmentMemberDao departmentMemberDao;

    @Override
    public ExcelVerifyHandlerResult verifyHandler(DepartmentMemberInput departmentMemberInput) {
        // 设置默认验证为true
        ExcelVerifyHandlerResult excelVerifyHandlerResult = new ExcelVerifyHandlerResult(true);
        // 1、检验excel中的数据和数据库中的数据是否重复
        // 根据姓名与手机号判断数据是否重复
        boolean isDuplicates = false;
        int count = departmentMemberDao.findByNameAndPhone(departmentMemberInput.getName(),departmentMemberInput.getPhone());
        if (count>0) {
            excelVerifyHandlerResult.setSuccess(false);
            excelVerifyHandlerResult.setMsg("姓名+手机号与数据库中数据重复");
            return excelVerifyHandlerResult;
        }
        // 2、校验excel中的数据是否重复
        List<DepartmentMemberInput> threadLocalVal = threadLocal.get();
        if (threadLocalVal == null) {
            threadLocalVal = new ArrayList<>();
        }
        for(DepartmentMemberInput memberInput :threadLocalVal){
            if(memberInput.equals(departmentMemberInput)){
                isDuplicates = true;
                break;
            }
        }
        // 添加本行数据对象到ThreadLocal中
        threadLocalVal.add(departmentMemberInput);
        threadLocal.set(threadLocalVal);
        if (isDuplicates) {
            excelVerifyHandlerResult.setSuccess(false);
            excelVerifyHandlerResult.setMsg("姓名+手机号与excel中数据重复");
            return excelVerifyHandlerResult;
        }
        return excelVerifyHandlerResult;
    }
    public ThreadLocal<List<DepartmentMemberInput>> getThreadLocal() {
        return threadLocal;
    }
}

